package com.crm.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.crm.domain.dto.LoginDTO;
import com.crm.domain.entity.User;
import com.crm.result.Result;
import com.crm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录控制器
 *
 * @author lucky
 */

@Controller
public class LoginController {

    @Resource
    private UserService service;

    // 登录
    @ResponseBody
    @RequestMapping("/login")
    public Result<User> login(LoginDTO loginDTO, HttpSession session, HttpServletResponse response) throws Exception {
        service.login(loginDTO, session, response);
        return Result.success();
    }

    // 退出登录
    @RequestMapping("/logout")
    public String logout(HttpServletResponse response, HttpSession session) {
        service.logout(session, response);
        return "login";
    }


    @ResponseBody
    @GetMapping("/captcha")
    public Result<String>  captcha(HttpServletRequest request) {
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40, 5, 100);

        // 验证码值
        String code = lineCaptcha.getCode();

        // 将验证码值保存到 session 中
        request.getSession().setAttribute("code", code);

        // 验证码以base64的格式返回到客户端
        return Result.success(lineCaptcha.getImageBase64());
    }
}
